<?php
require_once ('password.php');
require_once ('../../models/Products.php');
//session_start();

function GetConnection()
{
	global $password;
	$conn = new mysqli('localhost', 'n02585943', $password, 'n02585943_db');
	return $conn;
}


function EscapeRow($row, $conn)
{
	$row2 = array();
	foreach ($row as $key => $value) 
	{
		$row2[$key] = $conn->real_escape_string($value);			
	}
	return $row2;
}


function curl_download($Url){ 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}






//Cart
function writeShoppingCart() {
	$cart = $_SESSION['cart'];
	if (!$cart) {
		return '<p>You have no items in your shopping cart</p>';
	} else {
		// Parse the cart session variable
		$items = explode(',',$cart);
		$s = (count($items) > 1) ? 's':'';
		return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
	}
}

function showCart() {
	global $db;
	$total = 0;
	$cart = $_SESSION['cart'];
	if ($cart) {
		$items = explode(',',$cart);
		$contents = array();
		foreach ($items as $item) {
			$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
		}
		$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
		//$output[] = '<table>';
		$output[] = '<table class = "table table-bordered table-striped">';
		$output[] = '<tr><th>Action</th><th>Item</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
		foreach ($contents as $id=>$qty) {
			$row=Products::Get($id);
			//$sql = 'SELECT * FROM books WHERE id = '.$id;
			//$result = $db->query($sql);
			//$row = $result->fetch();
			//extract($row);
			$output[] = '<tr>';
			$output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
			$output[] = '<td>'.$row['Name'].'</td>';
			$output[] = '<td>$'.$row['Price'].'</td>';
			$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
			$output[] = '<td>$'.($row['Price'] * $qty).'</td>';
			$total += $row['Price'] * $qty;
			$_SESSION['total'] = $total;
			$output[] = '</tr>';
		}
		$output[] = '</table>';
		$output[] = '<p>Grand total: <strong>$'.$total.'</strong></p>';
		$output[] = '<div><button type="submit">Update cart</button></div>';
		$output[] = '</form>';
	} else {
		$output[] = '<p>You shopping cart is empty.</p>';
	}
	return join('',$output);
}
?>